package org.example.conf;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
// 授权服务器配置

/**
 * 协作对象: 授权服务器‌	安全配置的 AuthenticationManager
 *
 * 作用场景 : 验证用户身份（密码模式）
 */
@Configuration
@EnableAuthorizationServer // 来源: org.springframework.security.oauth2.config.annotation.web.configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;

    public AuthorizationServerConfig(AuthenticationManager authenticationManager,
                                     UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 令牌管理‌
     * 使用 TokenStore（如内存存储 InMemoryTokenStore）实现令牌的生成与存储，通过 tokenStore() 方法注入
     * @return
     */
    @Bean
    public TokenStore tokenStore() { // 来源: org.springframework.security.oauth2.provider.token
        return new InMemoryTokenStore(); //// 内存存储令牌
    }

    /**
     * 客户端认证管理‌
     * 通过 configure(ClientDetailsServiceConfigurer clients) 定义客户端凭证（client_id/client_secret）、授权类型（如密码模式）和权限范围（scopes）
     *          示例：
     *          clients.inMemory()
     *          .withClient("clientapp") // 客户端ID
     *          .secret(加密密码)         // 客户端密钥
     *          .authorizedGrantTypes("password", "refresh_token") // 支持的授权类型
     *          .scopes("read", "write") // 权限范围
     * @param clients the client details configurer
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("xr")       // 客户端ID
                .secret("{noop}112233")       // 客户端密钥（{noop}表示明文）
                .authorizedGrantTypes("password", "authorization_code", "refresh_token") // 授权模式:ml-citation{ref="5,7" data="citationList"}
                .scopes("read", "write")      // 权限范围
//                .redirectUris("http://localhost:8080/callback"); // 授权码模式回调地址:ml-citation{ref="7" data="citationList"}
                .redirectUris("https://www.baidu.com/callback/callback"); // 授权码模式回调地址:ml-citation{ref="7" data="citationList"}
    }

    /**
     * 端点配置‌
     * 在 configure(AuthorizationServerEndpointsConfigurer endpoints)
     * 中绑定认证管理器（AuthenticationManager）和用户详情服务（UserDetailsService），用于密码模式的用户身份验证
     * @param endpoints the endpoints configurer
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);  // 密码模式需绑定用户服务:ml-citation{ref="7,8" data="citationList"}
    }

    /**
     * ‌安全策略‌
     * 通过 configure(AuthorizationServerSecurityConfigurer security)
     * 开放令牌端点访问权限（如 /oauth/token）并允许表单认证
     * @param security a fluent configurer for security features
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("permitAll()") // 允许获取公钥
                .checkTokenAccess("isAuthenticated()")  // 验证令牌需认证
                .allowFormAuthenticationForClients();
    }
}
